package v1

import (
	"chat/internal/common/request"
	"chat/internal/common/response"
	"chat/internal/model"
	"chat/internal/service"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func GetAllGroup(c *gin.Context) {
	idStr, _ := c.GetQuery("uid")
	id, _ := strconv.Atoi(idStr)
	list, err := service.GetAllGroup(id)
	if err == nil {
		c.JSON(http.StatusOK, response.SuccessMsg(list))
		return
	}
	c.JSON(http.StatusOK, response.FailMsg("GetAllGroup failed"))
	return
}

func CreateGroup(c *gin.Context) {
	var req model.Group
	err := c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("参数获取失败"))
		return
	}
	// 查询是否有同名的群
	cnt, err := service.GetGroup(req)
	if cnt > 0 {
		c.JSON(http.StatusOK, response.FailMsg("群组名已存在"))
		return
	}

	// 创建群组
	err = service.CreateGroup(&req)
	err = service.AddMember(req.UserId, req.ID)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("CreateGroup err"))
		return
	}
	c.JSON(http.StatusOK, response.SuccessMsg(nil))
}

func GetGroupInfoByGroupId(c *gin.Context) {
	idStr, _ := c.GetQuery("id")
	id, _ := strconv.Atoi(idStr)
	g, err := service.GetGroupById(id)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("GetGroupById err"))
		return
	}
	memberIdList, err := service.GetUsersByGroupId(id)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("GetUsersByGroupId err"))
		return
	}
	c.JSON(http.StatusOK, response.SuccessMsg(gin.H{
		"groupInfo": g,
		"member":    memberIdList,
	}))
}

func UpdateGroupNotice(c *gin.Context) {
	var req request.EditGroupNoticeReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("获取参数失败"))
		return
	}
	err = service.UpdateGroupNotice(req.GroupId, req.GroupNotice)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("UpdateGroupNotice err"))
		return
	}
	c.JSON(http.StatusOK, response.SuccessMsg(nil))
}

func UpdateGroupName(c *gin.Context) {
	var req request.EditGroupNameReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("获取参数失败"))
		return
	}
	err = service.UpdateGroupName(req.GroupId, req.GroupName)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("UpdateGroupName err"))
		return
	}
	c.JSON(http.StatusOK, response.SuccessMsg(nil))
}
